package com.zs.framework.mail.runner;

import com.zs.framework.mail.annotation.MailProducer;
import com.zs.framework.mail.config.MailProperties;
import com.zs.framework.mail.producer.MailProducible;
import com.zs.framework.mail.utils.BeanNameUtils;
import com.zs.framework.mail.utils.MailHelper;
import com.zs.framework.mail.utils.SendEmailProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author zhougf
 * @version 1.0
 * @date 2020/07/23
 */
@Component
@Slf4j
public class MailRunner implements CommandLineRunner, DisposableBean {

    /**
     * 应用上下文注入
     */
    @Autowired
    private AbstractApplicationContext applicationContext;

    /**
     * Mail配置信息
     */
    @Autowired
    private MailProperties mailProperties;


    @Override
    public void destroy() throws Exception {
        log.info("MailRunner is destroy ......");
    }

    @Override
    public void run(String... args) throws Exception {
        String senderAddress = mailProperties.getSenderAddress();
        String userName = mailProperties.getUserName();
        String userPassword = mailProperties.getUserPassword();
        String protocol = mailProperties.getProtocol();
        String host = mailProperties.getHost();
        int port = mailProperties.getPort();
        BeanNameUtils.getBeanNamesByTypeWithAnnotation(MailProducible.class, MailProducer.class, applicationContext).forEach(name -> {
            MailProducible<?> mailProducible = applicationContext.getBeanFactory().getBean(name, MailProducible.class);
            MailProducer mailProducerAnn = applicationContext.findAnnotationOnBean(name, MailProducer.class);
            String receiveAddress = mailProducerAnn.receiveAddress();
            SendEmailProducer sendEmailProducer = MailHelper.getSendEmailProducer(senderAddress, receiveAddress, userName, userPassword, host, port, protocol);
            mailProducible.setSendMailProducer(sendEmailProducer);
        });
    }
}
